"use client";

import { useState } from "react";
import EastIcon from '@mui/icons-material/East';
import { useQueryClient, useMutation } from "@tanstack/react-query";
import axios from "axios";
import { useRouter } from "next/navigation";
import { useUser } from "@clerk/nextjs";

export default function Home() {
  const [input, setInput] = useState("");
  const [model, setModel] = useState("deepseek-v3");
  const handleChangeModel = () => {
    setModel(model === 'deepseek-v3' ? 'deepseek-r1' : 'deepseek-v3');
  };
  const queryClient = useQueryClient()
  const router = useRouter()
  const { user } = useUser()

  const { mutate: createChat } = useMutation({
    mutationFn: async () => {
      return axios.post('api/create-chat', {
        title: input,
        model: model
      })
    },
    onSuccess: (res) => {
      // Invalidate and refetch
      router.push(`/chat/${res.data.id}`)
      queryClient.invalidateQueries({ queryKey: ['chats'] })
      setInput(""); // 清空输入框
    },
  })

  const handleSubmit = () => {
    if (input.trim() === '') {
      return;
    }

    if (!user) {
      router.push('/sign-in')
      return;
    }
    createChat()
  }

  // 处理回车键提交
  const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSubmit();
    }
  };

  return (
    <div className="h-screen flex flex-col items-center bg-gray-50">
      <div className="h-1/5"></div>
      <div className="w-11/12 md:w-2/3 lg:w-1/2">
        <p className="text-bold text-3xl text-center text-blue-600 mb-6 font-semibold">
          有什么可以帮您的吗
        </p>

        <div className="flex flex-col items-center justify-center mt-4 shadow-md border-[1px] border-gray-200/80 rounded-lg bg-white/95 hover:shadow-lg transition-all duration-300 backdrop-blur-sm">
          <textarea
            className="w-full rounded-t-lg p-4 h-28 focus:outline-none resize-none bg-transparent"
            value={input}
            onChange={(e) => setInput(e.target.value)}
            onKeyDown={handleKeyDown}
            placeholder="请输入您想了解的内容..."
          >
          </textarea>
          <div className="flex flex-row items-center justify-between w-full h-12 px-3 py-2 bg-gray-50/90 rounded-b-lg border-t border-gray-100/80">
            <div>
              <div className={`flex flex-row items-center justify-center rounded-lg border-[1px] px-3 py-1.5 cursor-pointer transition-all duration-200 hover:shadow-sm ${model === 'deepseek-r1'
                ? "border-blue-400/80 bg-blue-50/90 text-blue-600"
                : "border-gray-300/70 hover:border-blue-300/80 hover:bg-blue-50/80"
                }`}
                onClick={handleChangeModel}
              >
                <p className="text-sm font-medium">
                  深度思考(R1)
                </p>
              </div>
            </div>
            <div className="flex items-center justify-center border-2 border-blue-500/80 p-1.5 rounded-full cursor-pointer hover:bg-blue-50/80 transition-all duration-200 hover:shadow-md"
              onClick={handleSubmit}
            >
              <EastIcon className="text-blue-500/90" />
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
